<template>
    <div>
        <h1>教师管理</h1>
        <el-dialog title="新增教师" :visible.sync="dialogFormVisible">
            <el-form :model="form" :rules="rules" ref="form">
                <el-form-item label="身份证号码" :label-width="formLabelWidth" prop="identity">
                    <el-input v-model="form.identity" autocomplete="off"></el-input>
                </el-form-item>
                <el-form-item label="手机号" :label-width="formLabelWidth" prop="phone">
                    <el-input v-model="form.phone" autocomplete="off"></el-input>
                </el-form-item>
                <el-form-item label="角色" :label-width="formLabelWidth" prop="rolesIds" >
                    <el-checkbox-group v-model="form.roleIds" >
                        <el-checkbox :label="teacherRole.id" :value="teacherRoles.id" v-for="teacherRole in teacherRoles">{{teacherRole.roleName}}</el-checkbox>
                    </el-checkbox-group>
                </el-form-item>
                <el-form-item label="姓名" :label-width="formLabelWidth" prop="name">
                    <el-input v-model="form.name" autocomplete="off"></el-input>
                </el-form-item>
                <el-form-item label="性别" :label-width="formLabelWidth" prop="sex">
                    <el-select v-model="form.sex" placeholder="请选择">
                        <el-option
                                v-for="item in options"
                                :key="item.sex"
                                :label="item.label"
                                :value="item.sex">
                        </el-option>
                    </el-select>
                </el-form-item>
            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button @click="dialogFormVisible = false">取 消</el-button>
                <el-button type="primary" @click="addTeacher">确 定</el-button>
            </div>
        </el-dialog>
        <el-col :gutter="20">
            <el-col :span="3"><el-button type="primary" @click="dialogFormVisible = true">新增教师</el-button></el-col>
            <el-col :span="1"><el-button type="danger" icon="el-icon-delete" @click="removeRows()">批量删除</el-button></el-col>
            <el-col :span="2" :offset="3"><el-button type="primary"  @click="exp">导出excel</el-button></el-col>
            <el-col :span="3" :offset="5">
                <el-select v-model="teacher.sex" placeholder="请选择性别" clearable>
                    <el-option
                            v-for="item in options"
                            :key="item.sex"
                            :label="item.label"
                            :value="item.sex">
                    </el-option>
                </el-select>
            </el-col>
            <el-col :span="3" :offset="1">
                <el-input v-model="teacher.name" placeholder="请输入姓名" clearable/>
            </el-col>
            <el-col :span="2" :offset="1">
                <el-button type="primary" icon="el-icon-search" @click="handleInitTeachers">搜索</el-button>
            </el-col>
        </el-col>

        <el-table :data="pageInfo.list" @selection-change="handleSelectionChange" style="width: 100%" :default-sort = "{prop: 'date', order: 'descending'}">
            <el-table-column
                    type="selection"
                    width="55">
            </el-table-column>
            <el-table-column
                    prop="name"
                    label="姓名"
                    width="180">
            </el-table-column>
            <el-table-column
                    prop="phone"
                    label="手机号"
                    width="180">
            </el-table-column>
            <el-table-column
                    label="性别"
                    width="180"
                    prop="sex">
            </el-table-column>
            <el-table-column
                    prop="inputCount"
                    label="登录次数"
                    width="180">
            </el-table-column>
            <el-table-column
                    prop="inputTime"
                    label="注册时间"
                    sortable
                    width="180">
                <template slot-scope="scope">
                    <span>{{scope.row.inputTime.toLocaleString().replace(/T/g, ' ').replace(/\.[\d]{3}Z/, '')}}</span>
                </template>
            </el-table-column>
            <el-table-column
                    label="是否在职"
                    width="180"
                    prop="onjob">
                <template slot-scope="scope">
                    <span>{{scope.row.onjob==true?"在职":"否"}}</span>
                </template>
            </el-table-column>
            <el-table-column align="center" label="操作" width="200" :resizable="false">
                <template slot-scope="{row}">
                    <el-button
                            type="primary"
                            size="small"
                            icon="el-icon-edit"
                            @click="handleUpdate(row.id)"
                    >修改</el-button>
                    <el-button
                            size="mini"
                            type="danger"
                            @click="handleDelete(row)"
                            icon="el-icon-delete">删除</el-button>
                </template>
            </el-table-column>
        </el-table>
        <el-pagination
                background
                layout="prev, pager, next"
                :current-page="pageNum"
                :page-size="pageInfo.pageSize"
                :total="pageInfo.total"
                @current-change="handleInitTeachers"
        >
        </el-pagination>
    </div>
</template>

<script>
    export default {
        name: "ManageTeacherView",
        data() {
            //验证身份证号
            let checkRegNo = (rule,value,callback) => {
                    var city={11:"北京",12:"天津",13:"河北",14:"山西",15:"内蒙古",21:"辽宁",22:"吉林",23:"黑龙江 ",31:"上海",32:"江苏",33:"浙江",34:"安徽",35:"福建",36:"江西",37:"山东",41:"河南",42:"湖北 ",43:"湖南",44:"广东",45:"广西",46:"海南",50:"重庆",51:"四川",52:"贵州",53:"云南",54:"西藏 ",61:"陕西",62:"甘肃",63:"青海",64:"宁夏",65:"新疆",71:"台湾",81:"香港",82:"澳门",91:"国外 "};
                    var tip = "";
                    var pass= true;
                    var patt1=new RegExp("(^[1-9]\\d{5}(18|19|([23]\\d))\\d{2}((0[1-9])|(10|11|12))(([0-2][1-9])|10|20|30|31)\\d{3}[0-9Xx]$)|(^[1-9]\\d{5}\\d{2}((0[1-9])|(10|11|12))(([0-2][1-9])|10|20|30|31)\\d{2}$)");
                    if(value == ''){
                        pass = true;
                    }else if(!patt1.test(value)){
                        callback(new Error("身份证号格式错误"));
                        pass = false;
                    } else if(!city[value.substr(0,2)]){
                        callback(new Error("地址编码错误"));
                        pass = false;
                    }else{
                        //18位身份证需要验证最后一位校验位
                        if(value.length == 18){
                            value = value.split('');
                            //∑(ai×Wi)(mod 11)
                            //加权因子
                            var factor = [ 7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2 ];
                            //校验位
                            var parity = [ 1, 0, 'X', 9, 8, 7, 6, 5, 4, 3, 2 ];
                            var sum = 0;
                            var ai = 0;
                            var wi = 0;
                            for (var i = 0; i < 17; i++)
                            {
                                ai = value[i];
                                wi = factor[i];
                                sum += ai * wi;
                            }
                            var last = parity[sum % 11];
                            if(parity[sum % 11] != value[17]){
                                callback(new Error("身份证号码错误"));
                                pass =false;
                            }
                        }
                    }
                    if(pass){
                        //判断
                        if(!this.form.id){
                            var str = "";
                            for(var i=0;i<value.length;i++){
                                str+= value[i]
                            }
                            this.$axios.post("/manage/teacher/identityRepeat",str,{headers:{'Content-Type': 'application/json'}}).then(response=>{
                                console.log(response.data.code==10001)
                                if(response.data.code==10001){
                                    callback(new Error("身份证号码已存在"));
                                    pass =false;
                                }
                            })
                        }
                        else {
                            callback();
                        }
                    }
                }
            return {
                teacherRoles:[],
                multipleSelection: [],
                imageUrl: '',
                pageNum:1,
                pageInfo:[],
                teacher:{},
                options: [{
                    sex: '男',
                    label: '男'
                },
                    {
                    sex: '女',
                    label: '女'
                }],
                sex:'男',
                dialogTableVisible: false,
                dialogFormVisible: false,
                form: {
                    identity:'',
                    sex:'男',
                    phone:'',
                    name:'',
                    roleIds:[1],
                },
                formLabelWidth: '100px',
                rules: {
                    name: [
                        {required: true, message: '请输入姓名', trigger: 'blur'}
                    ],
                    identity:[
                        { required: true, message: '身份证不能为空' },
                        { required: true,validator: checkRegNo, trigger: "blur" }
                    ],
                    phone:[
                        { required: true, message: '手机号不能为空' },
                        { type: 'number',
                            message: '手机号格式不正确',
                            trigger: 'blur',
                            transform (value) {
                                var phonereg = 11 && /^((13|14|15|16|17|18|19)[0-9]{1}\d{8})$/
                                if (!phonereg.test(value)) {
                                    return false
                                }else{
                                    return Number(value)
                                }
                            }
                        }
                    ],
                    roleIds:[
                        {required: true, message: '请选择教师角色', trigger: 'blur'}
                        ],
                },
            }
        },
        created() {
            this.handleInitTeachers();
            this.handleInitRoles();
        },
        methods: {
            //修改
            handleUpdate(id){
                this.$router.push('/manage/updateTeacher?id='+id);
            },
            // 当复选框选项发生变化的时候触发
            handleSelectionChange(selection) {
                this.multipleSelection = selection;
            },
            //批量删除
            removeRows() {
                this.$confirm("此操作将删除选中信息, 是否继续?", "提示", {
                    confirmButtonText: "确定",
                    cancelButtonText: "取消",
                    type: "warning"
                }).then(() => {
                    // 确定执行 then 方法
                   var idList = [];
                    // 遍历数组得到每个 id 值，设置到 idList 里面
                    for (var i = 0; i < this.multipleSelection.length; i++) {
                        var obj = this.multipleSelection[i];
                        var id = obj.id;
                        idList.push(id);
                    }
                    this.$axios.post('/manage/teacher/deleteBatch',idList).then(response => {
                        // 提示
                        this.$message({
                            type: "success",
                            message: "删除成功!"
                        });
                        // 刷新页面
                        this.handleInitTeachers();
                    });
                });
            },
            //删除
            handleDelete(row){
                this.$confirm('此操作将永久删除该教师, 是否继续?', '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                }).then(() => {
                    console.log(row.id);
                    this.$axios.get("http://localhost:8080/manage/teacher/delete",{params:{id: row.id}}).then(response => {
                        console.log(response);
                        if(response.data.code == 200){
                            /*this.tableData.splice(row,1);*/
                            this.handleInitTeachers();
                            this.$message({
                                type: 'success',
                                message: '删除成功!'
                            });
                        }
                        else{
                            this.$message({
                                showClose: true,
                                message: '删除出错啦',
                                type: 'error'
                            });
                        }
                    });
                }).catch(() => {
                    this.$message({
                        type: 'info',
                        message: '已取消删除'
                    });
                });
            },
            //添加
            addTeacher() {
                this.$refs['form'].validate((valid) => {
                    if (valid) {
                        this.$axios.post("http://localhost:8080/manage/teacher/save",this.form).then(response=>{
                            console.log(this.form.roleIds)
                            if(response.data.code == 10001){
                                this.$message({
                                    showClose: true,
                                    message: '该角色名已存在',
                                    type: 'error'
                                });
                            }
                            else if(response.data.code == 200){
                                this.handleInitTeachers();
                                this.dialogFormVisible = false;
                                this.$message({
                                    type: 'success',
                                    message: '添加成功!'
                                });
                            }
                        });
                    } else {
                        return false;
                    }
                });
            },
            //教师列表，分页，条件查询
            handleInitTeachers(pageNum){
                //如果刷新页面pageNum为undefined，如果点击搜索按钮pageNum为事件对象，如果点击分页的页面才是一个数字
                if(typeof pageNum == "number"){
                    this.pageNum = pageNum;
                }
                else{
                    this.pageNum=1;
                }
                this.loading = true;
                this.$axios.post("http://localhost:8080/manage/teacher/list",this.teacher,{params:{pageNum:this.pageNum}}).then(response=>{
                    this.pageInfo = response.data.data;
                });
            },
            //角色信息
            handleInitRoles(){
                this.$axios.get("http://localhost:8080/manage/role/list").then(response => {
                    this.teacherRoles = response.data.data;
                });
            },
            //导出
            exp(){
                // window.open("http://localhost:8080/manage/teacher/export");

                this.$axios.post("/manage/teacher/export",this.excelVule,{responseType:'blob'}).then(res => {
                    console.log(res)
                    const link = document.createElement('a')
                    const blob = new Blob([res.data], { type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8' })
                    link.style.display = 'none'
                    link.href = URL.createObjectURL(blob)
                    link.setAttribute('download', `教师.xlsx`)
                    document.body.appendChild(link)
                    link.click()
                    document.body.removeChild(link)
                    this.excelDlOpen = false;
                })
            }
        }
    }
</script>

<style scoped>

</style>